package Server;

import Server.Domain.Message;
import Server.Domain.MessageType;
import Server.Domain.User;
import ServerData.ServerOnlineData;
import ServerData.ServerTaskData;
import ServerData.ServerUserData;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

class ServerView{
    static ServerSocket serverSocket ;  //服务器退出才会销毁
    static ServerTaskData serverTaskData = new ServerTaskData();
    static ServerUserData serverUserData = new ServerUserData();
    static ServerOnlineData serverOnlineData = new ServerOnlineData();
    User user =  new User();
    Socket socket ;
    ObjectOutputStream oos;
    public void start(){
        try{
            serverSocket = new ServerSocket(9090);
        } catch (IOException e) {  //监听端口
            throw new RuntimeException(e);
        }
        new Thread(new ServerManager()).start();//服务端控制线程
        while(true) {
            //创建Socket对象,等待客户端连接;
            try {
                socket = serverSocket.accept();
                //一直停滞直至连接
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                user = (User) ois.readObject();

            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            //验证并返回
            Message messageBack = new Message();
            if (!serverUserData.checkUser(user.getName(), user.getPassword())) {
                //如果错误, 新建对象,返回
                messageBack.setMessageType(MessageType.LOGIN_FAIL);
                try{
                    oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(messageBack);
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                continue;//继续监听端口
            }
            messageBack.setMessageType(MessageType.LOGIN_SUCCESS);
            try{
                oos = new ObjectOutputStream(socket.getOutputStream());
                oos.writeObject(messageBack);

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //创建子线程持续监听已连接对象
            serverOnlineData.online(user);
            Task task = new Task();
            //为线程添加集合便于查找与管理
            serverTaskData.setTaskData(user, task);
            task.socket = socket;
            task.user = user;
            task.start();
        }
    }
}